<?php

class User extends Api
{
    protected $noNeedLogin = ['login'];

    public function login()
    {
        $name = $this->getParam('username');
        $pwd  = $this->getParam('password');
        if ($name == '' || $pwd == '') {
            $this->backJson([], ApiConst::BACK_LOGIN_EMPTY);
        }
        if (!checkName($name)) {
            $this->backJson([], ApiConst::BACK_LOGIN_ERROR);
        }
        $this->getDb()->where("name='{$name}'");
        $userInfo = $this->getDb()->getOne('users');
        //验证用户名密码是否正确
        $login = !empty($userInfo) && ($userInfo['pwd'] === encryptLogin($pwd));
        if (!$login) {
            $this->backJson([], ApiConst::BACK_LOGIN_ERROR);
        }
        $this->initUserInfo($userInfo);
        if ($this->isAdmin) {
            $roles = AuthConst::getAdminRoles();
        } else {
            $this->getDb()->where('id', $userInfo['role']);
            $roleInfo = $this->getDb()->getOne('roles', 'roles,pid');
            $roles  = explode(',', $roleInfo['roles']);
        }

        setcookie("token", $token = Jwt::getToken([
            'id'     => $userInfo['id'],
            'name'   => $userInfo['name'],
            'nick'   => $userInfo['nick'],
            'pid'    => $userInfo['pid'],
            'role'   => $userInfo['role'],
            'roles'  => array_map('intval', $roles),
            'expire' => time() + 86400 / 2,
            'time'   => time()
        ]));
        $this->backJson(['token' => $token], ApiConst::BACK_SUCCESS);
    }

    public function info()
    {
        $userInfo           = $this->userInfo;
        $userInfo['expire'] = date('Y-m-d H:i:s', $userInfo['expire']);
        $userInfo['token']  = $this->token;
        backJson($userInfo, ApiConst::BACK_SUCCESS);
    }

    public function logout()
    {
        setcookie('token', null);
        backJson([], ApiConst::BACK_SUCCESS);
    }

    public function add()
    {
        $name = $this->getParam('name');
        $pwd  = $this->getParam('pwd');
        $nick = $this->getParam('nick');
        $role = (int)$this->getParam('role');
        $max_num = (int)$this->getParam('max_num');
        if ($name == '' || $pwd == '') {
            $this->backJson([], ApiConst::BACK_LOGIN_EMPTY);
        }
        if (!checkName($name)) {
            $this->backJson([], ApiConst::BACK_LOGIN_ERROR);
        }
        if (!$this->isAdmin) {
            $this->getDb()->where("id={$role} and pid='{$this->userInfo['role']}'");
            $roleInfo = $this->getDb()->getOne('roles');
            if (empty($roleInfo)) {
                $this->backJson([], ApiConst::BACK_NOT_EXIST_ROLE);
            }
        }

        $this->getDb()->where("name='{$name}'");
        $info = $this->getDb()->getOne('users');
        if (!empty($info)) {
            $this->backJson([], ApiConst::BACK_EXIST_USER_NANE);
        }
        $userInfo = $this->userInfo;
        if ($this->getDb()->insert('users', [
            'pid'        => $userInfo['id'],
            'name'       => $name,
            'pwd'        => encryptLogin($pwd),
            'nick'       => $nick,
            'role'       => $role,
            'created_at' => time(),
            'time'       => strtotime(date('Y-m-d')),
            'max_num'    => $max_num
        ])) {
            $this->backJson([]);
        }
        $this->backJson([], ApiConst::BACK_CODE_ERROR);
    }


    public function edit()
    {
        $id   = $this->getParam('id');
        $pwd  = $this->getParam('pwd');
        $nick = $this->getParam('nick');
        $role = $this->getParam('role');
        $max_num = $this->getParam('max_num');
        $this->getDb()->where("id", $id);
        if (!$this->isAdmin) {
            $this->getDb()->where('pid', $this->isLogin);
        }
        $info = $this->getDb()->getOne('users');
        if (empty($info)) {
            $this->backJson([], ApiConst::BACK_NOT_EXIST_USER_NANE);
        }
        if (!$this->isAdmin) {
            $this->getDb()->where("id={$role} and pid='{$this->userInfo['role']}'");
            $roleInfo = $this->getDb()->getOne('roles');
            if (empty($roleInfo)) {
                $this->backJson([], ApiConst::BACK_NOT_EXIST_ROLE);
            }
        }
        $data = [];
        if ($pwd) {
            $data['pwd'] = encryptLogin($pwd);
        }
        if ($nick) {
            $data['nick'] = $nick;
        }
        $data['max_num'] = $max_num;
        $this->getDb()->where('id', $id);
        if (!$this->isAdmin) {
            $this->getDb()->where('pid', $this->isLogin);
        }
        if ($this->getDb()->update('users', $data)) {
            $this->backJson([]);
        }
        $this->backJson([], ApiConst::BACK_CODE_ERROR);
    }

    public function del()
    {
//        $id = $this->getParam('id');
//        $this->getDb()->where("id", $id);
//        $userInfo = $this->getDb()->getOne('users');
//        if (empty($userInfo)) {
//            $this->backJson([], ApiConst::BACK_NOT_EXIST_USER_NANE);
//        }
//        $this->getDb()->where("id", $id);
//        if ($this->getDb()->delete('users')) {
//            $this->backJson([]);
//        }
        $this->backJson([], ApiConst::BACK_CODE_ERROR);
    }

    public function list()
    {
        $page                     = (int)$this->getParam('page', 1);
        $pageSize                 = 20;
        $this->getDb()->pageLimit = $pageSize;
        $search_id                = $this->getParam('id', '');
        $search_name              = $this->getParam('name', '');
        $search_nick              = $this->getParam('nick', '');
        $search_status            = $this->getParam('status', '');
        if ($search_id !== '') {
            $this->getDb()->where('id', $search_id);
        }
        if ($search_name !== '') {
            $this->getDb()->where('name', '%' . $search_name . '%', 'like');
        }
        if ($search_nick !== '') {
            $this->getDb()->where('nick', '%' . $search_nick . '%', 'like');
        }
        if ($search_status !== '') {
            $this->getDb()->where('status', $search_status);
        }
        if (!$this->isAdmin) {
            $this->getDb()->where('pid', $this->isLogin);
        }
        $this->getDb()->orderBy('id');
        $list  = $this->getDb()->paginate("users", $page, 'id,name,nick,status,role,created_at,time,max_num,num');
        $total = $this->getDb()->totalCount;
        $roles = array_column($list, 'role');
        if ($roles) {
            $roles = array_unique($roles);
            $this->getDb()->where("id", $roles, 'in');
            $roleInfo = $this->getDb()->get('roles');
            $roleInfo = array_column($roleInfo, null, 'id');
        }
        foreach ($list as $k => $item) {
            $list[$k]['created_at'] = date('Y-m-d H:i:s', $item['created_at']);
            $list[$k]['role_name']  = $roleInfo[$item['role']]['name'];
            if (date('Y-m-d', $item['time']) != date('Y-m-d')) {
                $list[$k]['num'] = 0;
            }
            $list[$k]['role_name']  = $roleInfo[$item['role']]['name'];
        }
        $this->backJson([
            'list'      => $list,
            'total'     => (int)$total,
            'page'      => (int)$page,
            'totalPage' => (int)ceil($total / $pageSize),
            'pageSize'  => (int)$pageSize
        ]);
    }

    public function status()
    {
        $id     = (int)$this->getParam('id', 0);
        $status = (int)$this->getParam('status');
        if (!in_array($status, [0, 1])) {
            $this->backJson([], ApiConst::BACK_PARAM_ERROR);
        }
        $this->getDb()->where("id", $id);
        if (!$this->isAdmin) {
            $this->getDb()->where('pid', $this->isLogin);
        }
        $info = $this->getDb()->getOne('users', 'status');
        if ($info['status'] == $status) {
            $this->backJson([]);
        }
        $this->getDb()->where("id", $id);
        if (!$this->isAdmin) {
            $this->getDb()->where('pid', $this->isLogin);
        }
        $this->getDb()->update('users', ['status' => $status]);
        $this->backJson([]);
    }

    public function reset_pwd()
    {
        $pwd = $this->getParam('pwd', '');
        $this->getDb()->where('id', $this->userInfo['id']);
        if ($this->getDb()->update('users', ['pwd' => encryptLogin($pwd)])) {
            $this->backJson([]);
        }
        $this->backJson([], ApiConst::BACK_CODE_ERROR);
    }

    public function max_num()
    {
        $ids = $this->getParam('ids');
        $max_num = (int)$this->getParam('max_num');
        $ids = array_filter($ids);
        if ($max_num <= 300 && $max_num >= 0) {
            $this->getDb()->where("id", $ids, 'in');
            if (!$this->isAdmin) {
                $this->getDb()->where('pid', $this->isLogin);
            }
            $this->getDb()->update('users', ['max_num' => $max_num]);
            $this->backJson([]);
        }
        $this->backJson([], ApiConst::BACK_CODE_ERROR);
    }
}
